import 'package:flutter/material.dart';
import 'package:native_video_cache_example/optimized_cache_demo.dart';
import 'cache_demo.dart';
import 'video_player_demo.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Native Video Cache Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  // 演示视频列表
  static const List<VideoItem> demoVideos = [
    VideoItem(
      title: '示例视频 1 - 禁令标志',
      url:
          'https://new-jp.oss-cn-hangzhou.aliyuncs.com/jp_video/%E7%A7%91%E4%B8%802.2.2%E7%A6%81%E4%BB%A4%E6%A0%87%E5%BF%97.mp4',
    ),
    VideoItem(
      title: '示例视频 2 - 交通信号灯',
      url:
          'https://new-jp.oss-cn-hangzhou.aliyuncs.com/jp_video/%E7%A7%91%E4%B8%802.1.1%E4%BA%A4%E9%80%9A%E4%BF%A1%E5%8F%B7%E7%81%AF%E7%9A%84%E5%88%86%E7%B1%BB%E3%80%81%E6%9C%BA%E5%8A%A8%E8%BD%A6%E5%92%8C%E9%9D%9E%E6%9C%BA%E5%8A%A8%E8%BD%A6%E4%BF%A1%E5%8F%B7%E7%81%AF.mp4',
    ),
    VideoItem(
      title: '示例视频 3 - 旅游区标志',
      url:
          'https://new-jp.oss-cn-hangzhou.aliyuncs.com/jp_video/%E7%A7%91%E4%B8%802.2.5%E6%97%85%E6%B8%B8%E5%8C%BA%E3%80%81%E4%BD%9C%E4%B8%9A%E5%8C%BA%E3%80%81%E5%91%8A%E7%A4%BA%E3%80%81%E8%BE%85%E5%8A%A9%E6%A0%87%E5%BF%97.mp4',
    ),
    // 测试错误情况的视频
    VideoItem(
      title: '🧪 测试网络错误 - 无效URL',
      url: 'https://invalid-domain-for-testing-12345.com/test-video.mp4',
    ),
    VideoItem(
      title: '🧪 测试服务器错误 - 404',
      url: 'https://httpstat.us/404.mp4',
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('Native Video Cache 演示应用'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 应用介绍
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.video_library,
                          size: 32,
                          color: Theme.of(context).primaryColor,
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            'Native Video Cache 插件演示',
                            style: Theme.of(context).textTheme.titleSmall,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    const Text(
                      '本应用展示了 Native Video Cache 插件的完整功能：\n'
                      '• 视频缓存管理（基于 KTVHTTPCache & AndroidVideoCache）\n'
                      '• 视频播放器（基于 chewie & video_player）\n'
                      '• 缓存与播放的无缝集成',
                      style: TextStyle(fontSize: 14),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 24),

            // 功能演示区域
            Text(
              '功能演示',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const SizedBox(height: 16),

            // 缓存功能演示按钮
            _buildFeatureCard(
              context,
              icon: Icons.download,
              title: '缓存功能演示',
              subtitle: '体验视频缓存的完整流程',
              description: '包括缓存初始化、开始缓存、进度监听、状态管理、缓存清理等功能',
              onTap: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => const CacheDemo(),
                  ),
                );
              },
            ),

            const SizedBox(height: 16),

            // 优化的缓存管理演示按钮
            _buildFeatureCard(
              context,
              icon: Icons.auto_awesome,
              title: '优化的缓存管理演示',
              subtitle: '体验全新的智能缓存管理系统',
              description: '包括统一状态管理、智能错误处理、性能监控、依赖注入等优化功能',
              onTap: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => const OptimizedCacheDemo(),
                  ),
                );
              },
            ),

            const SizedBox(height: 16),

            // 播放器功能演示按钮
            _buildFeatureCard(
              context,
              icon: Icons.play_circle,
              title: '播放器功能演示',
              subtitle: '体验完整的视频播放功能',
              description: '包括播放控制、进度拖拽、速度调节、全屏播放、自定义控制层等功能',
              onTap: () {
                _showVideoSelector(context);
              },
            ),

            const SizedBox(height: 24),

            // 完整流程说明
            Card(
              color: Colors.blue.shade50,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.lightbulb_outline,
                          color: Colors.blue.shade700,
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            '完整体验流程建议',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.blue.shade700,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    const Text(
                      '1. 先进入"缓存功能演示"，选择视频进行缓存\n'
                      '2. 等待缓存完成后，再进入"播放器功能演示"\n'
                      '3. 播放已缓存的视频，体验流畅的本地播放效果\n'
                      '4. 也可以直接播放未缓存的视频，体验边播边缓存',
                      style: TextStyle(fontSize: 13),
                    ),
                  ],
                ),
              ),
            ),

            // 添加底部间距，确保最后的内容不会贴到屏幕底部
            const SizedBox(height: 24),
          ],
        ),
      ),
    );
  }

  Widget _buildFeatureCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required String description,
    required VoidCallback onTap,
  }) {
    return Card(
      clipBehavior: Clip.antiAlias,
      child: InkWell(
        onTap: onTap,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            children: [
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  icon,
                  size: 32,
                  color: Theme.of(context).primaryColor,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      subtitle,
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                            color: Colors.grey[600],
                          ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      description,
                      style: Theme.of(context).textTheme.bodySmall,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
              const Icon(
                Icons.arrow_forward_ios,
                size: 16,
                color: Colors.grey,
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _showVideoSelector(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.height * 0.8, // 最大高度为屏幕的80%
      ),
      builder: (context) => DraggableScrollableSheet(
        initialChildSize: 0.6, // 初始高度为60%
        minChildSize: 0.3, // 最小高度为30%
        maxChildSize: 0.8, // 最大高度为80%
        expand: false,
        builder: (context, scrollController) => Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
          ),
          child: Column(
            children: [
              // 拖拽指示器
              Container(
                margin: const EdgeInsets.symmetric(vertical: 8),
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),

              // 标题栏
              Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: Row(
                  children: [
                    Text(
                      '选择要播放的视频',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    const Spacer(),
                    IconButton(
                      onPressed: () => Navigator.pop(context),
                      icon: const Icon(Icons.close),
                    ),
                  ],
                ),
              ),

              // 可滚动的视频列表
              Expanded(
                child: ListView.builder(
                  controller: scrollController,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  itemCount: demoVideos.length,
                  itemBuilder: (context, index) {
                    final video = demoVideos[index];
                    return Card(
                      margin: const EdgeInsets.only(bottom: 8),
                      child: ListTile(
                        leading: Container(
                          width: 48,
                          height: 48,
                          decoration: BoxDecoration(
                            color:
                                Theme.of(context).primaryColor.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(
                            Icons.play_arrow,
                            color: Theme.of(context).primaryColor,
                          ),
                        ),
                        title: Text(
                          video.title,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        subtitle: Text(
                          video.url,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(fontSize: 12),
                        ),
                        trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                        onTap: () {
                          Navigator.pop(context); // 关闭底部表单
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => OptimizedCacheDemo(
                                videoUrl: video.url,
                                title: video.title,
                              ),
                              //     VideoPlayerDemo(
                              //   videoUrl: video.url,
                              //   title: video.title,
                              // ),
                            ),
                          );
                        },
                      ),
                    );
                  },
                ),
              ),

              // 底部安全区域
              SizedBox(height: MediaQuery.of(context).padding.bottom),
            ],
          ),
        ),
      ),
    );
  }
}

class VideoItem {
  final String title;
  final String url;

  const VideoItem({
    required this.title,
    required this.url,
  });
}
